package com.pmcc.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by Tomas on 2019/5/22.
 */
public class TranslateUtil {
    public static JSONObject TranslateAdd(String lat, String log ){
        //阿里云地图调用(100代表道路，010代表兴趣点，001代表门址，111可以同时显示前三项)
        //构造URL
        String urlString = "http://gc.ditu.aliyun.com/regeocoding?l="+lat+","+log+"&type=010";
        String res = "";
        try {
            //先进行请求
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置可输入
            conn.setDoOutput(true);
            //请求方式为POST
            conn.setRequestMethod("POST");
            //提取获得的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line+"\n";
            }
            //关闭连接
            in.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        if(res!=null&&!res.equals(""))
        {
            //此处可根据自己情况进行封装 此jsonObject为获得的所有数据构建的Json
            JSONObject jsonObject = JSONObject.fromObject(res);
            JSONArray jsonArray= JSONArray.fromObject(jsonObject.getString("addrList"));
            JSONObject j_2 = JSONObject.fromObject(jsonArray.get(0));
            String allAdd = j_2.getString("admName");
            String ssx[] = allAdd.split(",");
            if(ssx.length==3)
            {
                JSONObject address = new JSONObject();
                address.put("province", ssx[0]);
                address.put("city", ssx[1]);
                address.put("county", ssx[2]);
                System.err.println("省市县 "+ssx[0]+" "+ssx[1]+" "+" "+ssx[2]);
                return address;
            }
            return null;
        }else
        {
            return null;
        }
    }
    //百度地图，根据经纬度获得地址
    public static String getAddr(String lng,String lat)throws IOException{
        String ak="3AhUpEdu2Uw2BLRLEjAbx82UsVgxi6pK";//注册百度地图访问应用ak
        String url="http://api.map.baidu.com/geocoder/v2/?output=json&ak="+ak+"&location="+lng+","+lat;
        URL myUrl=null;
        String city="";
        String qx="";
        String address="";
        URLConnection httpsConn=null;
        try{
            myUrl=new URL(url);
        }catch (Exception e){
            e.printStackTrace();
        }
        InputStreamReader insr=null;
        BufferedReader br=null;
        try{
            httpsConn=(URLConnection)myUrl.openConnection();//不使用代理
            if(httpsConn!=null){
                insr=new InputStreamReader(httpsConn.getInputStream(),"UTF-8");
                br=new BufferedReader(insr);
                String data=null;
                while ((data=br.readLine())!=null){
                    JSONObject json=JSONObject.fromObject(data);
                    address=json.getJSONObject("result").getString("formatted_address");
                    city=json.getJSONObject("result").getJSONObject("addressComponent").getString("city");
                    qx=json.getJSONObject("result").getJSONObject("addressComponent").getString("district");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(insr!=null){
                insr.close();
            }
            if(br!=null){
                br.close();
            }
        }
        return address;
    }
    //百度地图，根据地址获得经纬度，测试结果经纬度反的（不知道原因）
    public static String[] getCoordinate(String addr)throws IOException{
        String ak="3AhUpEdu2Uw2BLRLEjAbx82UsVgxi6pK";//注册百度地图访问应用ak
        String lng=null;//经度
        String lat=null;//维度
        String address=null;
        try{
            address=java.net.URLEncoder.encode(addr,"UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        String url="http://api.map.baidu.com/geocoder/v2/?output=json&ak="+ak+"&address="+address;
        URL myUrl=null;
        URLConnection httpsConn=null;
        try{
            myUrl=new URL(url);
        }catch (Exception e){
            e.printStackTrace();
        }
        InputStreamReader insr=null;
        BufferedReader br=null;
        try{
            httpsConn=(URLConnection)myUrl.openConnection();
            if(httpsConn!=null){
                insr=new InputStreamReader(httpsConn.getInputStream(),"UTF-8");
                br = new BufferedReader(insr);
                String data=null;
                while ((data=br.readLine())!=null){
                    JSONObject json=JSONObject.fromObject(data);
                    lng=json.getJSONObject("result").getJSONObject("location").getString("lng");
                    lat=json.getJSONObject("result").getJSONObject("location").getString("lat");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(insr!=null){
                insr.close();
            }
            if(br!=null){
                br.close();
            }
        }
        return new String[]{lat,lng};
    }
    //计算距离
    public static double getDistance(double lat_a, double lng_a, double lat_b, double lng_b){
        double pk = 180 / 3.14169;
        double a1 = lat_a / pk;
        double a2 = lng_a / pk;
        double b1 = lat_b / pk;
        double b2 = lng_b / pk;
        double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
        double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
        double t3 = Math.sin(a1) * Math.sin(b1);
        double tt = Math.acos(t1 + t2 + t3);
        return 6371000 * tt;
    }
    public static void main(String[] args) {
        /*JSONObject a=TranslateUtil.TranslateAdd("34.350178", "108.949324");
        System.out.println(a.toString());*/
        try{
            System.out.println(TranslateUtil.getAddr( "34.86845781254432","113.66156019764094"));
            String[] s=TranslateUtil.getCoordinate("郑州师范学院");
            for(String st:s){
                System.out.println(st);
            }
        }catch (Exception e){

        }
    }

}
